﻿using Gavel.Common.Component.Helper;
using Gavel.Common.Utilities.Const;

namespace Gavel.ModLink.Model;

/// <summary>
/// RTU协议接收到报文
/// </summary>
public class ReceivedMessage
{
    /// <summary>
    /// 数据长度
    /// </summary>
    public byte DataLength { get; set; }

    /// <summary>
    /// 寄存器数据
    /// </summary>
    public List<byte[]> RegisterData { get; set; } = [];

    /// <summary>
    /// 报文
    /// </summary>
    public byte[] Message { get; }

    /// <summary>
    /// 构造方法统一处理接收到的报文
    /// </summary>
    /// <param name="message">报文</param>
    /// <param name="protocol">协议类型</param>
    public ReceivedMessage(byte[] message, ProtocolType protocol)
    {
        Message = message;
        byte code = protocol switch
        {
            ProtocolType.Tcp => message[7],
            _ => message[1]
        };

        if (code > 80)
        {
            NotifyHelper.Instance.Warning($"收到故障信息\n{((FaultCode)code).ToString()}");
            return;
        }

        switch (protocol)
        {
            case ProtocolType.Tcp:
                DataLength = message[8];
                RegisterData = Enumerable.Range(0, DataLength / 2).Select(index => message[(9 + index * 2)..(11 + index * 2)]).ToList();
                break;
            default:
                DataLength = message[2];
                RegisterData = Enumerable.Range(0, DataLength / 2).Select(index => message[(3 + index * 2)..(5 + index * 2)]).ToList();
                break;
        }
    }
}